package cn.labbook.bluetooth.util;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/8/4.
 */
public class DownloadUtils {


    public static <V> ResponseEntity<byte[]> downloadExcel(Class<V> clazz, List<V> list,
                                                           Map<String, String> map, String filename) throws Exception {

        if (!filename.endsWith(".xls")) {
            filename = filename + ".xls";
        }

        File file = buildExcelToFile(clazz, list, map, filename);
        ResponseEntity<byte[]> responseEntity = download0(file, filename);
        if (file.exists()) file.delete();
        return responseEntity;
    }

    private static <V> File buildExcelToFile(Class<V> clazz, List<V> list, Map<String, String> map, String filename) throws Exception {

        ExcelWriter writer = ExcelWriter.getDefaultExcelWriter();

        HSSFWorkbook hssfWorkbook = writer.write(clazz, list, map);

        String contextPath = System.getProperty("java.io.tmpdir");

        String cp = new StringBuffer(contextPath).append(contextPath.endsWith(File.separator) ? "" :
                File.separator).append("temp").append(File.separator).append("excel").toString();

        File temp = new File(cp);
        if (!temp.isDirectory())
            temp.mkdirs();

        File file = new File(new StringBuffer(cp).append(File.separator).append(filename).toString());

        hssfWorkbook.write(new FileOutputStream(file));

        return file;
    }


    public static ResponseEntity<byte[]> download0(File file, String filename) throws Exception {


        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        String downloadFileName = URLEncoder.encode(filename, "UTF-8");
        //通知浏览器以attachment（下载方式）打开zip
        headers.setContentDispositionFormData("attachment", downloadFileName);
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //兼容ie
       /*
        headers.setPragma("No-cache");
        headers.setCacheControl("No-cache");
        headers.setDate("Expires",0);*/

        return new ResponseEntity<>(FileCopyUtils.copyToByteArray(file), headers, HttpStatus.OK);

    }
    public static ResponseEntity<byte[]> download0(byte[] bytes, String filename) throws Exception {


        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        String downloadFileName = URLEncoder.encode(filename, "UTF-8");
        //通知浏览器以attachment（下载方式）打开zip
        headers.setContentDispositionFormData("attachment", downloadFileName);
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //兼容ie
       /*
        headers.setPragma("No-cache");
        headers.setCacheControl("No-cache");
        headers.setDate("Expires",0);*/

        return new ResponseEntity<>(bytes, headers, HttpStatus.OK);

    }

}
